package com.haskie.api.aop;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.*;
import java.util.*;


/**
 * Controller层AOP切面日志拦截打印输出
 */
@Slf4j
@Aspect
@Component
public class WebLogAcpect {

    public static final String EXCEPTION_HAS_LOGGED = "EXCEPTION_HAS_LOGGED";


    @Pointcut("execution(* com.haskie.*.controller..*.*(..))")
    public void point() {
        log.info("Controller层AOP日志切面拦截初始化...");
    }

    @Before("point()")
    public void doBefore(JoinPoint joinPoint) {

    }

    @Around(value = "point()")
    public Object invocation(ProceedingJoinPoint joinPoint) throws Throwable {

        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object result = joinPoint.proceed();
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setThreadName(Thread.currentThread().getName());
        requestInfo.setIp(request.getRemoteAddr());
        requestInfo.setUrl(request.getRequestURL().toString());
        requestInfo.setHttpMethod(request.getMethod());
        requestInfo.setClassMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName()));
        requestInfo.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
        requestInfo.setResult(result);
        requestInfo.setTimeCost(System.currentTimeMillis() - start);
        log.info("Request Info      : \n{}", cn.hutool.json.JSONUtil.formatJsonStr(JSON.toJSONString(requestInfo)));
        return result;
    }

    @AfterThrowing(pointcut = "point()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
        requestErrorInfo.setThreadName(Thread.currentThread().getName());
        requestErrorInfo.setIp(request.getRemoteAddr());
        requestErrorInfo.setUrl(request.getRequestURL().toString());
        requestErrorInfo.setHttpMethod(request.getMethod());
        requestErrorInfo.setClassMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName()));
        requestErrorInfo.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
        requestErrorInfo.setException(e);
        log.info("Error Request Info      : \n{}", cn.hutool.json.JSONUtil.formatJsonStr(JSON.toJSONString(requestErrorInfo)));
    }

    @After("point()")
    public void doAfter(JoinPoint joinPoint) {

    }

    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface IgnoreLogArgs {

    }


    /**
     * 获取参数
     *
     * @param joinPoint
     * @return
     */
    private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = joinPoint.getArgs();

        List<Object> argsForLog = new ArrayList<>(0);

        //过滤入参中的不可序列化对象
        for (Object arg : paramValues) {

            if (null == arg) {
                argsForLog.add(null);
                continue;
            }

            // Ignore ServletRequest
            if (ServletRequest.class.isAssignableFrom(arg.getClass())) {
                argsForLog.add(ServletRequest.class);
                continue;
            }

            // Ignore ServletResponse
            if (ServletResponse.class.isAssignableFrom(arg.getClass())) {
                argsForLog.add(ServletResponse.class);
                continue;
            }

            // Ignore HttpSession
            if (HttpSession.class.isAssignableFrom(arg.getClass())) {
                argsForLog.add(HttpSession.class);
                continue;
            }
            // Ignore HttpSession
            if (MultipartFile.class.isAssignableFrom(arg.getClass())) {
                argsForLog.add(HttpSession.class);
                continue;
            }

            argsForLog.add(arg);
        }

        return buildRequestParam(paramNames, argsForLog.toArray());
    }

    private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
        Map<String, Object> requestParams = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];

            //如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                value = file.getOriginalFilename();  //获取文件名
            }

            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }


    @Data
    public class RequestInfo {
        private String threadName;
        private String ip;
        private String url;
        private String httpMethod;
        private String classMethod;
        private Object requestParams;
        private Object result;
        private Long timeCost;
    }

    @Data
    public class RequestErrorInfo {
        private String threadName;
        private String ip;
        private String url;
        private String httpMethod;
        private String classMethod;
        private Object requestParams;
        private RuntimeException exception;
    }
}
